<template>
  <div class="outer">
    <div class="login">
      <h2>咖啡后台管理系统</h2>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="ruleForm.pass"
            @keyup.enter.native="submitForm('ruleForm')"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from "@/api/api";

export default {
  components: {},
  props: {},
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    var validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        username: "",
        pass: "",
      },
      rules: {
        username: [
          { required: true, validator: validateUsername, trigger: "blur" },
        ],
        pass: [{ required: true, validator: validatePass, trigger: "blur" }],
      },
    };
  },
  watch: {},
  computed: {},
  methods: {
    submitForm(formName) {
      login({ phone: this.ruleForm.username, password: this.ruleForm.pass })
        .then((result) => {
          if (localStorage.getItem("token")) {
            localStorage.removeItem("token");
          }
          // 存入token
          localStorage.setItem("token", result.data.data);
          this.$message({
            message: "登录成功！",
            type: "success",
          });
          // 跳转到主页
          setTimeout(() => {
            this.$router.push({ path: "/" });
          }, 1000);
        })
        .catch((err) => {
          console.log("err", err);
          this.$message({
            message: "登陆失败！",
            type: "error",
          });
        });
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="scss" scoped>
.outer {
  position: fixed;
  background-size: 100% 110%;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  .login {
    position: relative;
    width: 400px;
    height: 250px;
    left: 50%;
    top: 25%;
    margin-left: -200px;
    border-radius: 6px;
    background: #b9b7d3;
    padding-right: 50px;
    padding-top: 6px;
  }
  h2 {
    font-size: 1.5em;
    padding-bottom: 6px;
    font-family: "宋体";
    padding-left: 50px;
    color: #fff;
  }
}
</style>